package com.wanmait.gohome.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.gohome.mapper.ConfigMapper;
import com.wanmait.gohome.mapper.JournalMapper;
import com.wanmait.gohome.mapper.UserinfoMapper;
import com.wanmait.gohome.pojo.Config;
import com.wanmait.gohome.pojo.Journal;
import com.wanmait.gohome.pojo.Userinfo;
import com.wanmait.gohome.service.JournalService;
import com.wanmait.gohome.util.SysContext;
/*import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;*/
import org.apache.ibatis.annotations.Mapper;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class JournalServiceImpl implements JournalService {

    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private JournalMapper journalMapper;
    @Resource
    private HttpSolrClient client;
    @Resource
    private UserinfoMapper userinfoMapper;
    @Resource
    private ConfigMapper configMapper;


    @Override
    public PageInfo<Journal> findStopSeal() {
        int pageNum = SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Journal> journals = journalMapper.findStopSeal();
        PageInfo<Journal> pageInfo = new PageInfo<>(journals, 7);
        return pageInfo;
    }

    @Override
    public void removeEssay(Integer id) {
        journalMapper.removeEssay(id);
    }

    @Override
    public PageInfo<Journal> findTitlePageInfo(String title) {
        List<Journal> journals = new ArrayList<>();
        int pageNum = SysContext.getPageNum();
        int pageSize = 10;
//            PageHelper.startPage(pageNum, pageSize);
        PageInfo<Journal> pageInfo=null;
        try {
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery("title:"+title);
            //设置分页
            //从哪一条开始查询 (pageNum-1)*pagesize
            query.setStart((pageNum-1)*pageSize);
            //查询条数 pageSize
            query.setRows(pageSize);
            //设置高亮
            query.setHighlight(true);
            //设置高亮字段 可以用逗号分开指定多个高亮字段
            query.set("hl.fl", "title");
            //查询
            QueryResponse response = client.query("journal-manage",query);
            //获得高亮数据
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            Journal journal = null;
            Userinfo userinfo = null;
            //获得所有的文档集合
            SolrDocumentList documentList = response.getResults();
            for (SolrDocument document : documentList) {
                journal = new Journal();
                String id = (String) document.getFieldValue("id");
                journal.setId(Integer.parseInt(id));
                Integer ids = (Integer) document.getFieldValue("userinfoId");
                System.out.println("值"+ids);
                journal.setUserinfoId(ids);
                journal.setTitle(highlighting.get(id).get("title").get(0));
                journal.setEnable(true);
                Date inputTime = (Date) document.getFieldValue("inputTime");
                if (inputTime != null) {
                    journal.setInputTime(new Timestamp(inputTime.getTime()));
                }
                userinfo=userinfoMapper.findById(ids);
                journal.setUserinfo(userinfo);
                journals.add(journal);
            }
            pageInfo= new PageInfo<Journal>(journals,7);
            pageInfo.setPages(((int)documentList.getNumFound()-1)/pageSize+1);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pageInfo;


    }


    @Override
    public Journal findlogDetails(Journal journal) {

        return journalMapper.findinfo(journal);
    }

    @Override
    public void updateEnable(Journal journal) {
        journalMapper.updateEnbale(journal);
    }



    @Override
    public void insert(Journal object) {

    }

    @Override
    public void update(Integer id) {
        journalMapper.updateId(id);
    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void delete(String ids) {

    }

    @Override
    public List<Journal> findAll() {
        return null;
    }

    @Override
    public Journal findById(Integer id) {
        return null;
    }

    @Override
    public PageInfo<Journal> findPage() {//徐金鹏刚进去日志界面默认显示第一页
        int pageNum = SysContext.getPageNum();
        int pageSize = 4;
        PageHelper.startPage(pageNum, pageSize);
        List<Journal> journals = journalMapper.selcetList();
        PageInfo<Journal> pageInfo = new PageInfo<>(journals, 3);
        return pageInfo;
    }
    @Override
    public PageInfo<Journal> findByTitle(String titles) {//徐金鹏刚进去日志界面默认显示第一页
       List<Journal> journals = new ArrayList<>();
        int pageNum = SysContext.getPageNum();
        int pageSize = 4;
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Journal> pageInfo=null;

        try {
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery("title:"+titles);
            //设置分页
            //从哪一条开始查询 (pageNum-1)*pagesize
            query.setStart((pageNum-1)*pageSize);
            //查询条数 pageSize
            query.setRows(pageSize);
            //设置高亮
            query.setHighlight(true);
            //设置高亮字段 可以用逗号分开指定多个高亮字段
            query.set("hl.fl", "title");
            //查询
            QueryResponse response = client.query("journal",query);
            //获得高亮数据
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            Journal journal = null;
            Userinfo userinfo = null;
            //获得所有的文档集合
            SolrDocumentList documentList = response.getResults();
            for (SolrDocument document : documentList) {
                journal = new Journal();
                String id = (String) document.getFieldValue("id");
                journal.setId(Integer.parseInt(id));
                Integer ids = (Integer) document.getFieldValue("userinfoId");
                journal.setUserinfoId(ids);
                journal.setTitle(highlighting.get(id).get("title").get(0));
                journal.setEnable(true);
                String pic=(String) document.getFirstValue("pics");
                journal.setPics(pic);
                journal.setCommentCount((Integer) document.getFieldValue("commentCount"));
                journal.setBrowseCount((Integer)document.getFieldValue("browseCount"));
                journal.setLikeCount((Integer) document.getFieldValue("likeCount"));
                Date inputTime = (Date) document.getFieldValue("inputTime");
                if (inputTime != null) {
                    journal.setInputTime(new Timestamp(inputTime.getTime()));
                }
                 userinfo=userinfoMapper.findById(ids);
                journal.setUserinfo(userinfo);
                journals.add(journal);
            }
            pageInfo= new PageInfo<Journal>(journals,3);
            pageInfo.setPages(((int)documentList.getNumFound()-1)/pageSize+1);
            pageInfo.setPageNum(pageNum);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pageInfo;
    }

    @Override
    public void insertLike(int id) {//点赞数加一
        journalMapper.updateLikeCount(id);

        Double likeCount = redisTemplate.opsForZSet().score("todayHotJournals",id+"");
        if(likeCount==null)
        {
            redisTemplate.opsForZSet().add("todayHotJournals",id+"",1);
        }
        else
        {
            redisTemplate.opsForZSet().add("todayHotJournals",id+"",likeCount+1);
        }

    }

    @Override
      public void addById(int id) { //浏览数加一
        journalMapper.addDrowse(id);
    }

    @Override
    public Journal findByIds(int id) { //通过id查询出来对应日志的id
        return journalMapper.findByIds(id);
    }

    @Override
    public void sendLogs(Journal journal) {//发布日志书
        journalMapper.addRecord(journal);
    }


    /**
     *
     * @param userId   个人中心 查询所有日志
     * @return
     */
    @Override
    public PageInfo<Journal> findByUserId(Integer userId) {
        int pageNum = SysContext.getPageNum();
        int pageSize = 6;
        PageHelper.startPage(pageNum, pageSize);
        List<Journal> journals = journalMapper.findByUserId(userId);
        PageInfo<Journal> pageInfo = new PageInfo<>(journals, 5);
        return pageInfo;
    }


    /**
     *
     * @param journalId   个人中心 删除日志
     */
    @Override
    public void deleteByJournalId(Integer journalId) {
        journalMapper.deleteByJournalId(journalId);
    }


    /**
     *
     * @param count 今日最热日志
     * @return
     */
    @Override
    public List<Journal> findTodayHot(int count) {
        Set<String> idSet = redisTemplate.opsForZSet().reverseRange("todayHotJournals",0,count);
        if(idSet.size()==0){
            List<Journal> journals = journalMapper.selectByLikeCount();
            return journals;
        }else{
            List<Journal> journals = new ArrayList<>();
            for (String id:idSet)
            {
                Journal journal = journalMapper.selectListById(Integer.parseInt(id));
                journals.add(journal);
            }
            List<Journal> journals1 = journalMapper.selectByLikeCount();
            journals1.forEach(journal -> journals.add(journal));
            return journals;
        }
    }

    /**
     * 清空redis数据
     */
    @Override
    public void clearTodayHot() {
        redisTemplate.delete("todayHotJournals");
    }

    /**
     *
     * @param id 个人中心 首页  发布日志数量
     * @return
     */
    @Override
    public Integer findCountByUserId(Integer id) {
        return journalMapper.findCountByUserId(id);
    }

    /**
     *
     * @param journal  个人中心 修改日志
     */
    @Override
    public void updateByJournalId(Journal journal) {
        journalMapper.updateByJournalId(journal);
    }


    @Override
    public PageInfo<Journal> findtotal() {    //后台全部日志
        int pageNum = SysContext.getPageNum();
        int pageSize=0;

        try {
            Config config = configMapper.selectManagePageInteger();
            pageSize = Integer.parseInt(config.getConfigValue());//数据库里取
        } catch (NumberFormatException e) {
            pageSize=10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Journal> journals = journalMapper.findtotal();
        PageInfo<Journal> pageInfo = new PageInfo<>(journals, 7);
        return pageInfo;
    }


    @Override
    public List<Journal> findAll(Journal object) {
        return null;
    }

    @Override
    public PageInfo<Journal> findPage(Journal object) {
        return null;
    }
}
